(function() {
    'use strict';

    angular
        .module('byibserverApp')
        .directive('selectImg',selectImg);

        selectImg.$inject=['uploadImg'];

         function selectImg (uploadImg) {
            return {
                link:function (scope,ele,attr) {

                    var Imgstore=getStore(scope,attr.selectImg),
                        loadingState=getStore(scope,attr.loading),
                        loadingSuccessState=getStore(scope,attr.loadingSuccess);

                    function getStore(scope,str) {

                        var arr=str.split("."),
                            self=scope;

                        for(var i=0,len=arr.length-1;i<len;i++){
                            self=self[arr[i]];
                        }
                        return [self,arr[len]];

                    }
                    //console.log(scope,Imgstore,loadingState,loadingSuccessState)

                    ele[0].onchange=function (e) {


                        var reader = new FileReader();
                        var file = e.target.files[0];

                        reader.readAsDataURL(file);

                        reader.onload = function(e) {

                            var imgBase = e.target.result;

                            // console.log(data)

                            loadingState[0][loadingState[1]]=true;
                            loadingSuccessState[0][loadingSuccessState[1]]=false;

                            if (imgBase !== null) {
                                uploadImg.save(imgBase, onSaveSuccess, onSaveError);
                            }
                        };
                    };

                  function onSaveSuccess(data) {
                      Imgstore[0][Imgstore[1]]=data.image_link
                      loadingState[0][loadingState[1]]=false;
                      loadingSuccessState[0][loadingSuccessState[1]]=true;
                      console.log( Imgstore[0])
                  }
                  function onSaveError(error) {
                      loadingState[0][loadingState[1]]=false;
                      loadingSuccessState[0][loadingSuccessState[1]]=false;
                      console.log(error);
                      alert("上传图片出错了，请重试")
                  }
                }
            }
        }
})();
